<template>
  <div class="tree-table-container">
    <slot name="bottomTool"></slot>
    <div
      ref="tableContainer"
      class="table-container"
      :style="{
        height: props?.tableConfig?.tableH,
        paddingTop: props?.tableConfig?.tableType === 'project' ? '16px' : '0',
      }"
    >
      <!-- 连线删除悬浮窗 -->
      <div
        v-if="showLinkDeletePopup"
        class="link-delete-popup"
        :style="{
          left: linkDeletePopupPosition.left + 'px',
          top: linkDeletePopupPosition.top + 'px',
        }"
        @click.stop
      >
        <div class="popup-content">
          <div class="delete-action" @click="handleLinkDelete">删除连线</div>
        </div>
      </div>
    </div>

    <div
      class="pagination-container"
      v-if="tableConfig?.page?.enable && props.pageQuery"
    >
      <el-pagination
        v-model:current-page="props.pageQuery.pageNo"
        v-model:page-size="props.pageQuery.pageSize"
        :page-sizes="tableConfig?.page?.pageSizes"
        :size="tableConfig?.page?.size"
        :disabled="tableConfig?.page?.disabled"
        :background="tableConfig?.page?.background"
        :layout="
          tableConfig?.page?.layout || 'total, sizes, prev, pager, next, jumper'
        "
        :total="props?.pageQuery?.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <MoreActionsPopup
      v-if="hasAvailableActions"
      :visible="showMoreActionsPopup"
      :position="moreActionsPopupPosition"
      :actions="moreActions"
      :row="selectedNode"
      @close="closeMoreActionsPopup"
      @action="handleMoreAction"
    />
    <TaskStatusPopup
      :visible="statusVisible"
      :position="position"
      :actions="actions"
      @close="statusVisible = $event"
      @action="handleStatusAction"
    />
  </div>
</template>

<script setup lang="ts">
  import {
    computed,
    inject,
    nextTick,
    onMounted,
    onUnmounted,
    ref,
    watch,
  } from "vue";
  import * as VTable from "@visactor/vtable";
  import * as VTableGantt from "@visactor/vtable-gantt";
  import { registerCustomEditors } from "./register/index.ts";
  import { getIconForType, settingIcon } from "@/utils/SvgIcons";
  import MoreActionsPopup from "@/components/MoreActionsPopup.vue";

  import type {
    ColumnConfig,
    DynamicField,
    ProjectNode,
    SoftwareNode,
    TreeNodeData,
  } from "./interface.ts";
  import {
    createStatusLayout,
    getFieldType,
    getTypeGroup,
  } from "@/components/CLTable/index.ts";
  import TaskStatusPopup from "@/components/TaskStatusPopup.vue";

  // 定义props
  interface TableProps {
    fields: DynamicField[];
    activeTab?: number;
    // 从父组件传递的初始数据
    initialData?: ProjectNode[] | SoftwareNode[];
    initialLinks?: [];
    pageQuery?: Record<string, any>;
    // 行高设置
    lineHeight?: "low" | "medium" | "high";
    tableConfig?: Record<string, any>;
    routerFields?: string[];

    // 时间维度显示配置
    timeScalesToShow?: Array<"year" | "month" | "week" | "day">;

    // 增删改钩子函数
    onAddNode?: (parentNode: ProjectNode, newNode: ProjectNode) => void;
    onDeleteNode?: (node: ProjectNode) => void;
    onUpdateNode?: (node: ProjectNode, field: string, value: any) => void;

    // 更多操作菜单配置
    moreActions?: Array<{ key: string; label: string }>;
    // 更多操作回调函数
    onMoreAction?: (actionKey: string, node: ProjectNode) => void;
  }

  // 接收props
  const props = defineProps<TableProps>();

  // 定义事件
  const emit = defineEmits<{
    "update:initialData": [data: ProjectNode[]];
    "update:saveField": [data: ProjectNode[]];
    "view-node-detail": [node: ProjectNode];
    "node-selected": [nodes: ProjectNode[]];
    "show:records": [nodes: ProjectNode[]];
    "edit-node": [node: ProjectNode];
    "delete-node": [node: ProjectNode];
    "add-child-node": [parentNode: ProjectNode];
    "show:parentRecord": [record: ProjectNode];
    "on-more-action": [actionKey: string, node: ProjectNode, args?: any];
    pagerChange: [pager: { currentPage: number; pageSize: number }];
  }>();

  // 容器引用
  const tableContainer = ref<HTMLDivElement | null>(null);
  let tableInstance: any = null;
  let leftTableInstance: any = null;
  const searchKeyword = ref("");
  const originalData = ref<ProjectNode[]>([]);

  // 分页相关状态
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);

  // 从父组件注入显示字段配置弹窗的函数
  const showFieldConfigPopup = inject<
    (position: { left: number; top: number }) => void
  >("showFieldConfigPopup");

  // 定义moreIcon悬浮窗相关状态
  const showMoreActionsPopup = ref(false);
  const moreActionsPopupPosition = ref({ left: 0, top: 0 });
  const selectedNode = ref<ProjectNode | null>(null);
  const currentRowIndex = ref(-1);
  const currentColIndex = ref(-1);

  // 临时存储当前点击行的数据
  const tempCurrentRowData = ref<ProjectNode | null>(null);

  // 定义连线删除悬浮窗相关状态
  const showLinkDeletePopup = ref(false);
  const linkDeletePopupPosition = ref({ left: 0, top: 0 });
  const selectedLink = ref<any>(null);

  // 使用父组件提供的moreActions配置，如果没有提供则为空数组
  const moreActions = computed(() => props.moreActions || []);

  // 检查是否有可用的操作菜单
  const hasAvailableActions = computed(() => moreActions.value.length > 0);

  // 计算要显示的时间维度配置
  const computedScales = computed(() => {
    // 所有可用的时间维度配置
    const allScales = [
      {
        unit: "year",
        step: 1,
        format(date: any) {
          return `${date.dateIndex}年`;
        },
        style: {
          fontSize: 12,
          fontWeight: "400",
          color: "#111827",
          textAlign: "center",
          backgroundColor: "#FFF",
        },
      },
      {
        unit: "month",
        step: 1,
        format(date: any) {
          return VTableGantt.tools.formatDate(
            new Date(date.startDate),
            "    yyyy年mm月",
          );
        },
        style: {
          textStick: true,
          fontSize: 12,
          fontWeight: "400",
          color: "#111827",
          textAlign: "start",
          textBaseline: "middle",
          backgroundColor: "#FFF",
        },
      },
      {
        unit: "week",
        step: 1,
        startOfWeek: "monday",
        format(date: any) {
          return `第 ${date.dateIndex} 周`;
        },
        style: {
          fontSize: 12,
          fontWeight: "400",
          color: "#111827",
          textAlign: "center",
          backgroundColor: "#FFF",
        },
      },
      {
        unit: "day",
        step: 1,
        format(date: any) {
          return VTableGantt.tools.formatDate(new Date(date.startDate), "dd");
        },
        style: {
          fontSize: 12,
          fontWeight: "400",
          color: "#111827",
          textAlign: "center",
          backgroundColor: "#FFF",
        },
      },
    ];

    // 如果没有指定显示的时间维度，默认显示所有
    if (!props.timeScalesToShow || props.timeScalesToShow.length === 0) {
      return allScales;
    }

    // 根据指定的时间维度过滤显示
    return allScales.filter((scale) =>
      props.timeScalesToShow?.includes(scale.unit as any),
    );
  });

  const updatePopupPositionOnScrollOrResize = () => {
    if (
      showMoreActionsPopup.value &&
      currentRowIndex.value >= 0 &&
      currentColIndex.value >= 0 &&
      tableInstance
    ) {
      try {
        const rect = tableInstance.getCellRect(
          currentColIndex.value,
          currentRowIndex.value,
        );
        const tableRect = tableContainer.value?.getBoundingClientRect();

        if (rect && tableRect) {
          const leftPos =
            (tableRect.left || 0) +
            (rect.x || 0) +
            (rect.width || 0) -
            20 +
            (window.scrollX || 0);
          const topPos =
            (tableRect.top || 0) +
            (rect.y || 0) +
            (rect.height || 0) / 2 +
            (window.scrollY || 0);

          const popupWidth = 160;
          const popupHeight = 200;

          let adjustedLeft = leftPos;
          let adjustedTop = topPos;

          if (adjustedLeft + popupWidth > window.innerWidth) {
            adjustedLeft = window.innerWidth - popupWidth - 10;
          }
          if (adjustedLeft < 0) {
            adjustedLeft = 10;
          }
          if (adjustedTop + popupHeight > window.innerHeight) {
            adjustedTop = window.innerHeight - popupHeight + 20;
          }
          if (adjustedTop < 0) {
            adjustedTop = 10;
          }

          moreActionsPopupPosition.value = {
            left: adjustedLeft,
            top: adjustedTop,
          };
        }
      } catch (error) {
        console.error("更新悬浮窗位置失败:", error);
        // 出错时关闭悬浮窗
        closeMoreActionsPopup();
      }
    }
  };

  // 关闭更多操作悬浮窗
  const closeMoreActionsPopup = () => {
    showMoreActionsPopup.value = false;
    statusVisible.value = false;
    selectedNode.value = null;
    currentRowIndex.value = -1;
    currentColIndex.value = -1;
  };

  // 处理连线右键点击事件，显示删除悬浮窗
  const handleLinkContextMenu = (args: any) => {
    const { link, event } = args;
    selectedLink.value = link;

    // 设置悬浮窗位置，适配碰撞
    if (!tableContainer.value) return;
    const rect = tableContainer.value.getBoundingClientRect();
    const left = event.clientX - rect.left + 10;
    const top = event.clientY - rect.top + 10;

    // 简单的碰撞检测，确保悬浮窗不会超出视口
    const popupWidth = 120;
    const popupHeight = 40;
    const containerWidth = rect.width;
    const containerHeight = rect.height;

    linkDeletePopupPosition.value = {
      left: Math.min(left, containerWidth - popupWidth),
      top: Math.min(top, containerHeight - popupHeight),
    };
    setTimeout(() => {
      showLinkDeletePopup.value = true;
    }, 300);
  };

  // 关闭连线删除悬浮窗
  const closeLinkDeletePopup = () => {
    showLinkDeletePopup.value = false;
    selectedLink.value = null;
  };

  // 处理删除连线操作
  const handleLinkDelete = () => {
    if (selectedLink.value) {
      emit("on-more-action", "linkDelete", selectedLink.value);
      closeLinkDeletePopup();
    }
  };

  // 处理更多操作菜单中的操作
  const handleMoreAction = (actionKey: string) => {
    console.log("handleMoreAction", actionKey);
    if (!selectedNode.value) return;

    // 发送on-more-action事件给父组件
    emit("on-more-action", actionKey, selectedNode.value);
    closeMoreActionsPopup();
  };

  // 添加子节点的方法
  const addChildNode = (tableInstance: any, parentRecord: ProjectNode) => {
    console.log("addChildNode", parentRecord);
    // 确保 parentRecord 存在
    if (!parentRecord) return;

    // 把父 id/no 拆成数组，例如 '1-2' -> [1, 2]
    const parentParts = parentRecord.seq
      ? parentRecord.seq.split("-").map((n) => parseInt(n, 10))
      : [];

    // 计算下一个子编号（数值），优先用 children 长度或解析最大子编号防止不连续的场景
    let nextChildNum = 1;
    if (parentRecord.children && parentRecord.children.length > 0) {
      // 用 children 中最后一个的编号（假设 children 已经按顺序且编号连续）
      const maxNum = parentRecord.children.reduce((m, c) => {
        const parts = (c.seq || c.no).split("-");
        return Math.max(m, parseInt(parts[parts.length - 1], 10) || 0);
      }, 0);
      nextChildNum = maxNum + 1;
    }

    // 构造 new id/no，例如 parent '1-2' + nextChildNum 3 => '1-2-3'
    const newNo =
      parentParts.length > 0
        ? `${parentParts.join("-")}-${nextChildNum}`
        : `${nextChildNum}`;

    const newChild: ProjectNode = {
      id: newNo,
      seq: newNo,
      no: newNo,
      name: "",
      priority: [],
      status: "",
      startDate: "",
      endDate: "",
      assignee: "",
      parentRecord: parentRecord.name,
      date: "",
      isChecked: false,
      children: [],
    };

    const tmpFlag = false;
    // 如果父组件提供了添加节点的钩子函数，调用它
    if (props.onAddNode && tmpFlag) {
      props.onAddNode(parentRecord, newChild);
    } else if (tableInstance) {
      // 否则使用默认的添加逻辑
      // 构造 addRecord 需要的索引路径（zero-based）
      // parentParts: [1,2] -> parent zero-based path = [0,1], new child's index = nextChildNum - 1
      const parentZeroPath = parentParts.map((n) => n - 1);
      const subIds = [...parentZeroPath, nextChildNum - 1];

      // 如果父节点没有 children，先创建（保证数据结构完整）
      if (!parentRecord.children) parentRecord.children = [];

      // 用 tableInstance.addRecord 插入（或者直接 push 到 tableOption.value.records）
      tableInstance.addRecord(newChild, subIds);
    }

    // 触发update事件，让父组件可以同步更新数据
    emit("on-more-action", "addChild", parentRecord);
  };

  const initData = () => {
    if (props.initialData) {
      originalData.value = JSON.parse(JSON.stringify(props.initialData));
      originalData.value.map((item) => ({
        ...item,
        _vtable_rowSeries_number: false,
      }));
      // 设置总条数
      total.value = props.initialData.length;
    } else {
      originalData.value = [];
      total.value = 0;
    }
  };

  initData();

  // 监听初始数据变化
  // 分页事件处理函数
  const handleSizeChange = (newSize: number) => {
    // 分页事件不涉及特定节点，第二个参数使用null
    emit("pagerChange", {
      currentPage: 1, // 重置为第一页
      pageSize: newSize,
    });
    // emit("on-more-action", "paginationSizeChange", null as any);
  };

  const handleCurrentChange = (newPage: number) => {
    emit("pagerChange", {
      currentPage: newPage,
      pageSize: props.pageQuery.pageSize,
    });
    // 分页事件不涉及特定节点，第二个参数使用null
    // emit("on-more-action", "paginationCurrentChange", null as any);
  };

  watch(
    () => props.initialData,
    (newData) => {
      initData();
      if (tableInstance) {
        tableInstance.setRecords(originalData.value);
        //  applyLineHeight();
        dataSource = new VTable.data.CachedDataSource({
          records: originalData.value,
          canChangeOrder: canChangeOrder,
          changeOrder: changeOrder,
        });
        tableInstance.dataSource = dataSource;
        applyLineHeight();
      }
    },
    { deep: true },
  );

  // 应用行高设置
  const applyLineHeight = () => {
    // 检查是否是甘特图模式
    const isGanttMode = props.tableConfig?.mode === "gantt";
    let height = 40; // 默认高度
    switch (props.lineHeight) {
      case "low":
        height = 40;
        break;
      case "medium":
        height = 56;
        break;
      case "high":
        height = 72;
        break;
    }
    const rows = props.fields || [];
    rows.forEach((_, rowIndex) => {
      if (rowIndex > 0) {
        if (isGanttMode && leftTableInstance) {
          // 设置左侧表格行高
          leftTableInstance.setRowHeight(rowIndex, height);
          setTimeout(() => {
            tableInstance.scenegraph.refreshAll();
          }, 100);
        } else if (!isGanttMode && tableInstance) {
          // 设置普通表格行高
          // console.log("rowIndex", rowIndex, height);
          setTimeout(() => {
            tableInstance.setRowHeight(rowIndex, height);
          }, 100);
        }
      }
    });

    // 甘特图模式下，更新配置中的行高
    if (isGanttMode && props.tableConfig) {
      // tableInstance.updateOption(props.tableConfig);
    }
  };

  // 监听行高变化
  watch(
    () => props.lineHeight,
    () => {
      setTimeout(() => {
        applyLineHeight();
      }, 1000);
      if (tableInstance) {
        applyLineHeight();
      }
    },
    { immediate: true },
  );

  watch(
    () => props.tableConfig?.timelineHeader?.colWidth,
    (newv) => {
      if (!tableInstance) return;
      tableInstance.release();
      tableInstance.options.timelineHeader.colWidth = newv;
      initTable(false);
    },
    { immediate: true },
  );
  watch(
    () => props.tableConfig?.editable,
    () => {
      if (!tableInstance) return;
      if (props.tableConfig?.mode === "gantt")
        tableInstance.taskListTableInstance.updateColumns(dynamicColumns.value);
      else tableInstance.updateColumns(dynamicColumns.value);
    },
  );
  // 基础列配置
  const baseColumns = computed<ColumnConfig[]>(() => []);
  // {
  //   field: props.fields[0].field,
  //   title: props.fields[0].name,
  //   width: props.fields[1].width || 160,
  //   tree: props?.tableConfig?.tree || false,
  //   style: {
  //     paddingLeft: (datum: TreeNodeData) => {
  //       const level = datum.level || 0;
  //       return `${level * 20 + 10}px`;
  //     },
  //   },
  // },
  // {
  //   field: props.fields[1].field,
  //   title: props.fields[1].name,
  //   width: props.fields[1].width || 220,
  //   // icon: ["view"],
  //   style: {
  //     color: "#0070BA",
  //     cursor: "pointer",
  //   },
  // },
  // ]);

  // 根据字段类型适配列配置
  const getColumnConfigByType = (field: DynamicField): ColumnConfig | null => {
    const tableLib =
      props.tableConfig?.mode === "gantt"
        ? VTableGantt.VRender
        : VTable.CustomLayout;
    const isGantt = props.tableConfig?.mode === "gantt";
    const tableField = field.field;
    const tableType = getFieldType(field.uiType);
    let isRouterField = false;
    if (props.routerFields) {
      isRouterField = props.routerFields.includes(tableField);
    }

    // 根据tableConfig.typeIconShow决定是否显示头部图标
    const getHeaderIconConfig = () => {
      const shouldShowIcon = props.tableConfig?.typeIconShow === true;
      return shouldShowIcon
        ? [
            {
              type: "svg",
              marginRight: 4,
              positionType: VTable.TYPES.IconPosition.contentLeft,
              width: 14,
              height: 14,
              svg: getIconForType(field.uiType),
            },
          ]
        : undefined;
    };
    if (isRouterField) {
      // console.log("props?.routerFields", props.routerFields);
      // console.log("isRouterField", isRouterField);
      // console.log("tableField", tableField);
    }

    if (!tableField) return null;

    // 操作项特殊处理
    if (tableField === "operations") {
      if (props?.tableConfig?.OperationsColumnMode === "text") {
        return {
          field: tableField,
          title: field.name,
          width: props?.tableConfig?.OperationsColumnWidth || "auto",
          style: {},
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            props,
            {
              onActionClick: (key: string, row: any) => {
                emit("on-more-action", key, tempCurrentRowData.value || row);
              },
              onNeedRender: () => {
                tableInstance.render();
              },
            },
            field,
          ),
          headerIcon: [
            {
              type: "svg",
              name: "setting",
              positionType: VTable.TYPES.IconPosition.contentRight,
              width: 14,
              height: 14,
              marginLeft: props?.tableConfig?.OperationsColumnWidth / 2 - 35,
            },
          ],
        };
      } else if (props?.tableConfig?.OperationsColumnMode === "textIcon") {
        return {
          field: tableField,
          title: field.name,
          width: props?.tableConfig?.OperationsColumnWidth || "auto",
          style: {},
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            props,
            {
              onActionClick: (key: string, row: any) => {
                emit("on-more-action", key, tempCurrentRowData.value || row);
              },
              onNeedRender: () => {
                tableInstance.render();
              },
            },
            field,
          ),
          headerIcon: [
            {
              type: "svg",
              name: "settingIcon",
              positionType: VTable.TYPES.IconPosition.absoluteRight,
              width: 14,
              height: 14,
              svg: settingIcon.replace(/currentColor/g, "#BFBFBF"),
              cursor: "pointer",
            },
          ],
        };
      } else {
        return {
          field: tableField,
          title: "",
          width: props?.tableConfig?.OperationsColumnWidth || 35,
          style: {
            justifyContent: "center",
            padding: "0",
          },
          customLayout: props.moreActions?.length
            ? createStatusLayout(
                tableField,
                tableType,
                tableLib,
                props,
                {
                  hasAvailableActions: () => hasAvailableActions.value,
                  onMoreClick: ({ record, row, col, popupPosition }) => {
                    showMoreActionsPopup.value = false;
                    selectedNode.value = record as ProjectNode;
                    currentRowIndex.value = row;
                    currentColIndex.value = col;
                    setTimeout(() => {
                      showMoreActionsPopup.value = true;
                      moreActionsPopupPosition.value = popupPosition;
                    }, 100);
                  },
                },
                field,
              )
            : undefined,
          headerIcon: [
            {
              type: "svg",
              name: "settingIcon",
              positionType: VTable.TYPES.IconPosition.contentLeft,
              width: 16,
              height: 16,
              marginLeft: -2,
              svg: settingIcon.replace(/currentColor/g, "#BFBFBF"),
              cursor: "pointer",
            },
          ],
        };
      }
    }
    // 基于字段类型的配置
    switch (tableType) {
      case "text":
      case "textarea":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable ? "input-editor" : undefined,
          fieldFormat(rec: ProjectNode) {
            return tableField === "taskTypeVO"
              ? (rec as any)[tableField].name.zh_CN
              : (rec as any)[tableField] || "";
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {
            color: isRouterField ? "#0070BA" : "#1D2129",
            cursor: isRouterField ? "pointer" : "default",
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "imagetext":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable ? "input-editor" : undefined,
          fieldFormat(rec: ProjectNode) {
            return (rec as any)[tableField] || "";
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {
            color: isRouterField ? "#0070BA" : "#1D2129",
            cursor: isRouterField ? "pointer" : "default",
          },
          headerIcon: getHeaderIconConfig(),
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            props,
            field,
          ),
        };

      case "number":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable ? "input-editor" : undefined,
          fieldFormat(rec: ProjectNode) {
            const type = getTypeGroup(field.uiType);
            let integerRegex = /^(0|[-+]?[1-9]\d*)$/;
            if (type === "float") integerRegex = /^-?\d+\.\d+([eE][-+]?\d+)?$/;
            const displayName = (rec as any)[tableField] || 0;
            if (!displayName || !integerRegex.test(displayName)) {
              return ((rec as any)[tableField] = "");
            }
            return (rec as any)[tableField] || "";
          },
          style: {
            color: isRouterField ? "#0070BA" : "#1D2129",
            cursor: isRouterField ? "pointer" : "default",
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          headerIcon: getHeaderIconConfig(),
        };

      case "multiple":
        // 多选类型配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable
            ? "custom-multiple-select"
            : undefined,
          fieldFormat(rec: ProjectNode) {
            const displayName = field?.format;
            if (!displayName) return "";
            return rec?.[tableField]?.join(", ");
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {
            justifyContent: "center",
            borderRadius: "4px",
          },
          headerIcon: getHeaderIconConfig(),
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            undefined,
            undefined,
            field,
          ),
        };

      case "single":
        // 单选类型配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable
            ? tableField === "taskStatus"
              ? undefined
              : "custom-single-select"
            : undefined,
          fieldFormat(rec: ProjectNode) {
            return rec.status;
          },
          style: {
            justifyContent: "center",
            borderRadius: "4px",
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          headerIcon: getHeaderIconConfig(),
          customLayout:
            tableField === "taskStatus"
              ? createStatusLayout(
                  tableField,
                  tableType,
                  tableLib,
                  undefined,
                  {
                    onActionClick: (record, popupPosition) => {
                      if (props.tableConfig?.editable === false) return;
                      selectedNode.value = record as ProjectNode;
                      console.log("onActionClick", record, popupPosition);
                      setTimeout(() => {
                        statusVisible.value = true;
                        position.value = popupPosition;
                        actions.value = record.transferEdge.map(
                          (item: any) => ({
                            ...item,
                            taskId: record.id,
                          }),
                        );
                      }, 100);
                    },
                  },
                  field,
                )
              : createStatusLayout(
                  tableField,
                  tableType,
                  tableLib,
                  undefined,
                  {
                    onActionClick: (key: string, record: any) => {
                      if (props.tableConfig?.editable === false) return;
                      console.log("onActionClick", key, record);
                      emit("on-more-action", key, record);
                    },
                  },
                  field,
                ),
        };
      case "date":
        // 日期类型配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || (originalData?.value?.length ? 140 : "auto"),
          editor: props.tableConfig?.editable
            ? "custom-element-plus-date"
            : undefined,
          fieldFormat(rec: ProjectNode) {
            return (rec as any)[tableField] || "";
          },
          style: {},
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "checkbox":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          cellType: tableType,
          checked: field.checked || false,
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {
            justifyContent: "center",
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "image":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          cellType: tableType,
          keepAspectRatio: true,
          imageAutoSizing: true,
          style: {
            justifyContent: "center",
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "link":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          linkJump: field.linkJump || false,
          cellType: tableType,
          templateLink: field.tableField || "",
          style: {
            justifyContent: "center",
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "switch":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          cellType: tableType,
          checked: field.checked || false,
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          checkedText: field.checkedText || "是",
          uncheckedText: field.uncheckedText || "否",
          style: {
            justifyContent: "center",
            color: "#fff",
            fontSize: 12,
            switchStyle: {
              boxHeight: 20,
            },
          },
          headerIcon: getHeaderIconConfig(),
        };
      case "user":
        // 用户类型配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: undefined,
          style: {
            justifyContent: "center",
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            undefined,
            {
              onActionClick: (key: string, record: any) => {
                if (props.tableConfig?.editable === false) return;
                emit("on-more-action", key, record);
              },
            },
          ),
          headerIcon: getHeaderIconConfig(),
        };

      case "selectUser":
        // 用户类型配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable
            ? getTypeGroup(field.uiType) === "multiple"
              ? "custom-multiple-select"
              : "custom-single-select"
            : undefined,
          style: {
            justifyContent: "center",
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            undefined,
            {},
            field,
          ),
          headerIcon: getHeaderIconConfig(),
        };
      case "progress":
        return {
          field: tableField,
          title: field.name,
          width: field.width || (originalData?.value?.length ? 120 : "auto"),
          style: {},
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          customLayout: createStatusLayout(
            tableField,
            tableType,
            tableLib,
            undefined,
            undefined,
            field,
          ),
          headerIcon: getHeaderIconConfig(),
        };
      case "fn":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          fieldFormat(rec: ProjectNode) {
            return (rec as any)[tableField] || "";
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {},
          headerIcon: getHeaderIconConfig(),
        };
      case "language":
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable ? "input-editor" : undefined,
          fieldFormat(rec: ProjectNode) {
            return (rec as any)[tableField].zh_CN || "";
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {
            color: isRouterField ? "#0070BA" : "#1D2129",
            cursor: isRouterField ? "pointer" : "default",
          },
          headerIcon: getHeaderIconConfig(),
        };
      default:
        // 默认配置
        return {
          field: tableField,
          title: field.name,
          width: field.width || "auto",
          editor: props.tableConfig?.editable ? "input-editor" : undefined,
          fieldFormat(rec: ProjectNode) {
            return (rec as any)[tableField] || "";
          },
          disable: (args: any): boolean => {
            return isFieldDisabled(field, args);
          },
          style: {},
          headerIcon: getHeaderIconConfig(),
        };
    }
  };

  // 动态生成表格列配置
  const dynamicColumns = computed<ColumnConfig[]>(() => {
    if (!props.fields || props.fields.length === 0) {
      // 如果没有传入fields，返回默认列
      return [];
    }

    // 从baseColumns开始构建列配置
    const columnsConfig: ColumnConfig[] = [...baseColumns.value];

    props.fields.forEach((field) => {
      if (field.name === "id") return;

      // 如果字段不可见，跳过
      if (!field.invisible) return;
      const columnConfig = getColumnConfigByType(field);
      if (columnConfig) {
        if (props?.tableConfig?.tree?.enabled) {
          const currentColumnIndex =
            baseColumns.value.length + columnsConfig.length;
          if (currentColumnIndex === props.tableConfig.tree.column - 1) {
            columnConfig.tree = true;
            if (!columnConfig.style) columnConfig.style = {};
            if (props.tableConfig.tree.mode === "wbs") {
              columnConfig.icon = ["add", "view"];
              columnConfig.width = 240;
            }
            if (typeof columnConfig.style === "object") {
              columnConfig.style.paddingLeft = (datum: TreeNodeData) => {
                const level = datum.level || 0;
                return `${level * 20 + 10}px`;
              };
            }
          }
        }
        columnsConfig.push(columnConfig);
      }
    });

    // 默认显示操作列
    const shouldShowOperationsColumn =
      props?.tableConfig?.showOperationsColumn !== false;
    if (shouldShowOperationsColumn) {
      const operationsField = {
        id: 999,
        name: "操作",
        field: "operations",
        type: "string",
        invisible: true,
      } as DynamicField;

      const operationsColumn = getColumnConfigByType(operationsField);
      if (operationsColumn) {
        columnsConfig.push(operationsColumn);
      }
    }

    return columnsConfig;
  });

  let mode: any = {
    dragHeaderSplitLine: {
      lineColor: "transparent",
      lineWidth: 0,
      shadowBlockColor: "transparent",
    },
    defaultStyle: {
      borderLineWidth: 0,
    },
    headerStyle: {
      bgColor: "#FFF",
      borderColor: "#F2F3F5",
      borderLineWidth: 1,
      fontWeight: "normal",
      color: "#1f2329",
      fontSize: 14,
      hover: {
        cellBgColor: "#F7F8FA",
      },
    },
    bodyStyle: {
      borderColor: "#F2F3F5",
      bgColor: "#FFF",
      borderLineWidth: 1,
      color: "#1D2129",
      fontSize: 13,
      hover: {
        cellBgColor: "#F6F7FA",
        inlineRowBgColor: "#F6F7FA",
        inlineColumnBgColor: "#F6F7FA",
      },
      select: {
        inlineRowBgColor: "#F6F7FA",
      },
    },
    selectionStyle: {
      cellBgColor: "rgba(255, 255, 255,0.1)",
      cellBorderLineWidth: 2,
      cellBorderColor: "#3073f2",
    },
    frameStyle: {
      borderColor: "#F2F3F5",
      borderLineWidth: 1,
      borderLineDash: [],
      cornerRadius: 0,
      shadowBlur: 0,
      shadowOffsetX: 0,
      shadowOffsetY: 0,
      shadowColor: "#FFF",
      verticalSplitLine: {
        borderColor: "#F2F3F5",
        borderLineWidth: 1,
      },
    },
    cellInnerBorder: false,
  };

  if (props.tableConfig?.borderMode === "none") {
    mode.headerStyle.borderLineWidth = 0;
    mode.bodyStyle.borderLineWidth = [1, 0];
    mode.frameStyle.borderLineWidth = 0;
    mode.headerStyle = {
      bgColor: "#FFF",
      borderColor: "#FFF",
      borderLineWidth: 0,
      fontWeight: "normal",
      color: "#999999",
      fontSize: 12,
      hover: {
        cellBgColor: "#FFF",
      },
    };
    mode.scrollStyle = {
      scrollRailColor: "rgba(246,246,246,0.1)",
      visible: "focus",
      width: 6,
      horizontalVisible: "focus",
      hoverOn: false,
      scrollSliderCornerRadius: 2,
      scrollSliderColor: "#cecece",
      barToSide: true,
      ignoreFrozenCols: true,
    };
  }
  const wbsTheme = VTable.themes.ARCO.extends(mode);
  function normalizePath(raw: number | number[] | undefined): number[] | null {
    if (raw == null) return null;
    return Array.isArray(raw) ? [...raw] : [raw];
  }
  function adjustFrozenCount(columns: any, tableWidth: number = 360) {
    let frozenCount = props.tableConfig?.frozenCount || 0;
    let totalWidth = 0;
    // 逐列累加宽度，直到超出 tableWidth
    for (let i = 0; i < columns.length; i++) {
      const columnWidth = columns[i].width;
      let width: number;
      if (columnWidth === "auto" || columnWidth === undefined) {
        width = 150;
      } else if (typeof columnWidth === "string") {
        // 处理其他可能的字符串值
        width = parseInt(columnWidth, 10) || 150;
      } else {
        width = columnWidth;
      }
      totalWidth += width;
      if (totalWidth > tableWidth) {
        frozenCount = i; // 超出则不包含当前列
        break;
      }
    }
    // 保证最少冻结1列
    return Math.max(frozenCount, 1);
  }
  // 定义表格选项
  const tableOption = computed(() => {
    // 默认配置
    const defaultConfig = {
      rowResizeType: "row",
      rowResizeMode: "all",
      dragOrder: {
        dragHeaderMode: "row",
      },
      frozenColCount: 0,
      rightFrozenColCount: 0,
      overscrollBehavior: "none",
      hover: {
        highlightMode: "row",
        disableHeaderHover: true,
      },
      heightMode: "standard",
      tooltip: {
        isShowOverflowTextTooltip: true,
      },
      autoFillWidth: true,
      autoFillHeight: false,
      menu: {
        contextMenuItems: ["添加子记录", "删除"],
      },
      defaultHeaderRowHeight: 40,
      defaultRowHeight: 40,
      // records: originalData.value.map((record) => ({
      //   ...record,
      //   _vtable_rowSeries_number: false, // 默认未选中
      // })),
      dataSource: dataSource,
      columns: dynamicColumns.value,
      widthMode: "standard",
      autoWrapText: false,
      theme: wbsTheme,
      editCellTrigger: "doubleclick",
      enableLineBreak: true,
      // 配置树形结构的关键参数
      tree: {
        childrenKey: "children",
      },
      select: {
        disableHeaderSelect: true,
        disableSelect: false,
      },
      rowSeriesNumber: {
        width: "auto",
        // format: (col?: number, row?: number, table?: any) => {
        //   if (
        //     table &&
        //     typeof (table as any).getRecord === "function" &&
        //     row !== undefined
        //   ) {
        //     const record = (table as any).getRecord(row);
        //     return record ? record.id : "";
        //   }
        //   return "";
        // },
        format: () => {
          return "";
        },
        cellType: "checkbox",
        enableTreeCheckbox: true,
        dragOrder: false,
      },
      scrollStyle: {
        scrollRailColor: "rgba(246,246,246,0.1)",
        visible: "focus",
        width: 6,
        horizontalVisible: "focus",
        hoverOn: false,
        scrollSliderCornerRadius: 2,
        scrollSliderColor: "#cecece",
        barToSide: true,
        ignoreFrozenCols: true,
      },
      emptyTip: {
        text: "暂无数据",
        textStyle: {
          fontSize: 10,
          fontWeight: 400,
          color: "#42464E",
          lineHeight: 0,
        },
        icon: {
          width: 40,
          height: 30,
        },
      },
    } as Record<string, any>;

    // 创建最终配置对象，先应用用户自定义配置
    let finalConfig = defaultConfig;

    // 只有在甘特图模式或wbs模式下才使用dataSource
    const isGanttMode = props.tableConfig?.mode === "gantt";
    const isWbsMode = props.tableConfig?.tree?.mode === "wbs";
    if (isGanttMode || isWbsMode) {
      finalConfig.dataSource = dataSource;
    }

    if (props.tableConfig?.mode === "gantt") {
      // 应用用户自定义配置

      // 如果是甘特图模式，添加甘特图特定配置
      // 使用类型断言确保TypeScript允许添加甘特图特定属性
      // 重要：甘特图需要使用headerRowHeight和rowHeight而不是defaultHeaderRowHeight和defaultRowHeight
      // 先保存行高值，因为我们会从finalConfig中过滤掉这些属性
      const headerRowHeightValue = finalConfig.defaultHeaderRowHeight || 40;
      const rowHeightValue = finalConfig.defaultRowHeight || 40;
      finalConfig = {
        // 移除不兼容的属性
        ...Object.fromEntries(
          Object.entries(finalConfig).filter(
            ([key]) =>
              !["defaultHeaderRowHeight", "defaultRowHeight"].includes(key),
          ),
        ),
        // 添加甘特图特定的行高属性
        headerRowHeight: headerRowHeightValue,
        rowHeight: rowHeightValue,
        taskListTable: {
          dragOrder: {
            dragHeaderMode: "row",
          },
          menu: {
            contextMenuItems: ["添加子记录", "删除"],
          },
          tooltip: {
            isShowOverflowTextTooltip: true,
          },
          editCellTrigger: "doubleclick",
          theme: wbsTheme,
          columns: dynamicColumns.value,
          tableWidth: props.tableConfig?.taskListTable?.tableWidth || 360,
          minTableWidth: 100,
          frozenColCount: adjustFrozenCount(
            dynamicColumns.value,
            props.tableConfig?.taskListTable?.tableWidth,
          ),
          // frozenColCount: props.tableConfig?.frozenColCount ?? 2,
          select: {
            disableHeaderSelect: true,
            disableSelect: false,
          },
          hover: {
            highlightMode: "row",
            disableHeaderHover: true,
          },
          emptyTip: {
            text: "暂无数据",
            textStyle: {
              fontSize: 10,
              fontWeight: 400,
              color: "#42464E",
              lineHeight: 0,
            },
            icon: {
              width: 40,
              height: 30,
            },
          },
        },
        tasksShowMode: VTableGantt.TYPES.TasksShowMode.Tasks_Separate,
        taskBar: {
          selectable: true,
          startDateField: "plannedStartTime",
          endDateField: "plannedEndTime ",
          progressField: "progress",
          labelText: "{name} ({progress}%)",
          labelTextStyle: {
            fontFamily: "Arial, sans-serif",
            fontSize: 12,
            textAlign: "left",
            color: "#1D2129",
          },
          hoverBarStyle: {
            barOverlayColor: "rgba(255, 255, 255, 0.3)",
          },
          barStyle: (value: any) => {
            const { taskRecord } = value;
            const progress = taskRecord.progress || 0;
            // console.log('barStyle', taskRecord.progress);
            return {
              width: 24,
              barColor: "#E4F4FF",
              completedBarColor: progress >= 100 ? "#1AA1FB" : "#C9E9FF",
              cornerRadius: 2,
              borderWidth: 1,
              // borderColor: "#d1d5db",
            };
          },
          progressAdjustable: false,
          milestoneStyle: {
            labelText: "{name}",
            fillColor: (value: any) =>
              value.record.progress >= 100 ? "#597ef7" : "#d6e4ff",
            // borderColor: "",
            borderLineWidth: 0,
            width: 16,
            labelTextStyle: {
              fontSize: 12,
              color: "#1D2129",
              textAlign: "left",
              padding: 10,
            },
          },
        },
        minDate: "",
        maxDate: "",
        frame: {
          verticalSplitLineMoveable: true,
          outerFrameStyle: {
            cornerRadius: 0,
          },
          verticalSplitLine: {
            lineWidth: 1,
            top: 0,
            lineColor: "#d1d5db",
          },
          verticalSplitLineHighlight: {
            lineColor: "#3b82f6",
            lineWidth: 1,
          },
        },
        timelineHeader: {
          verticalLine: {
            lineWidth: 1,
            lineColor: "#d1d5db",
          },
          horizontalLine: {
            lineWidth: 1,
            lineColor: "#d1d5db",
          },
          backgroundColor: "#fff",
          colWidth: 100,
          scales: computedScales.value,
        },
        timeline: {
          format: "YYYY-MM-DD",
          zoomLevels: [
            { label: "日", unit: "day", pixelPerUnit: 60 },
            { label: "周", unit: "week", pixelPerUnit: 60 * 7 },
            { label: "月", unit: "month", pixelPerUnit: 60 * 30 },
            { label: "季", unit: "quarter", pixelPerUnit: 60 * 90 },
            { label: "年", unit: "year", pixelPerUnit: 60 * 365 },
          ],
        },
        markLine: [
          {
            date: new Date().toISOString().slice(0, 10),
            content: " 今天 ",
            contentStyle: {
              color: "#fff",
            },
            style: {
              lineWidth: 0.7,
              lineColor: "red",
              lineDash: [5, 5],
            },
          },
        ],
        grid: {
          verticalLine: {
            lineWidth: 0.5,
            lineColor: "#e1e4e8",
          },
          horizontalLine: {
            lineWidth: 0.5,
            lineColor: "#e1e4e8",
          },
        },
        dependency: {
          linkCreatable: true,
          linkDeletable: true,
          links: props.initialLinks ?? [],
          linkLineStyle: {
            lineColor: "#999999",
          },
        },
      };
    }
    if (props.tableConfig) {
      const tableConfig = props.tableConfig;
      Object.keys(tableConfig).forEach((key) => {
        if (
          typeof tableConfig[key] === "object" &&
          tableConfig[key] !== null &&
          typeof finalConfig[key] === "object" &&
          finalConfig[key] !== null &&
          !Array.isArray(tableConfig[key]) &&
          !Array.isArray(finalConfig[key])
        ) {
          finalConfig[key] = { ...finalConfig[key], ...tableConfig[key] };
        } else {
          finalConfig[key] = tableConfig[key];
        }
      });
    }
    return finalConfig;
  }) as any;
  let dataSource = new VTable.data.CachedDataSource({
    records: originalData.value,
    canChangeOrder: canChangeOrder,
    // 执行拖拽后的数据调整
    changeOrder: changeOrder,
  });
  function canChangeOrder(sourceRow: number, targetRow: number) {
    return props.tableConfig?.rowSeriesNumber?.dragOrder;
  }
  function changeOrder(sourceRow: number, targetRow: number) {
    try {
      const newTableInstance =
        props.tableConfig?.mode === "gantt" ? leftTableInstance : tableInstance;
      const headerCount = newTableInstance.columnHeaderLevelCount || 0;
      // 获取原始路径
      const srcRaw = newTableInstance.getRecordIndexByCell(
        0,
        sourceRow + headerCount,
      );
      const tgtRaw = newTableInstance.getRecordIndexByCell(
        0,
        targetRow + headerCount,
      );
      const sourcePath = normalizePath(srcRaw)!;
      const targetPath = normalizePath(tgtRaw)!;

      // 获取记录
      const record = newTableInstance.getRecordByCell(
        0,
        sourceRow + headerCount,
      );
      const targetRecord = newTableInstance.getRecordByCell(
        0,
        targetRow + headerCount,
      );
      if (record && targetRecord) {
        console.log("changeOrder", record, targetRecord);
        const dragData = {
          draggedId: record.originData?.idChain || record.idChain || record.id,
          targetId:
            targetRecord.originData?.idChain ||
            targetRecord.idChain ||
            targetRecord.id,
          position: blueLineDiv?.dataset.type || "after",
        };
        emit("drag-completed", dragData);
      }

      // 删除源节点
      const sourceParentPath = sourcePath.slice(0, -1);
      if (sourceParentPath.length === 0) {
        // 顶层节点
        newTableInstance.deleteRecords(sourcePath);
      } else {
        newTableInstance.deleteRecords([sourcePath]);
      }
      // 插入节点
      const isChildDrop = blueLineDiv?.dataset.type;
      if (isChildDrop === "child") {
        // 插入目标节点子节点
        // (dataSource as any).addRecordsForTree([record], targetPath);
        if (!targetRecord.children) {
          targetRecord.children = [record];
        } else {
          targetRecord.children.push(record);
        }
        newTableInstance.updateRecords(targetRecord);
      } else {
        if (sourcePath.length > 1) {
          console.log(
            tgtRaw,
            newTableInstance.getTableIndexByBodyIndex(0, tgtRaw),
          );
          newTableInstance.addRecord(
            record,
            newTableInstance.getTableIndexByBodyIndex(0, tgtRaw).row,
          );
        } else {
          newTableInstance.addRecord(record, tgtRaw);
        }
      }
      originalData.value = JSON.parse(JSON.stringify(newTableInstance.records));
      emit("update:initialData", originalData.value);
      // 刷新表格
      // newTableInstance.scenegraph.updateNextFrame();
    } catch (err) {
      console.error("changeOrder 出现未捕获异常：", err);
    }
  }

  //通过路径获取节点
  function getNodeByPath(records: any[], path: number[]): any | null {
    let node: any = null;
    let current = records;
    for (let i = 0; i < path.length; i++) {
      const idx = path[i];
      if (!current || idx >= current.length) return null;
      node = current[idx];
      current = node.children || [];
    }
    return node;
  }

  // 存储选中的节点ID集合
  const selectedNodeIds = ref<Set<string>>(new Set());

  // 递归选中所有子节点
  const selectChildNodes = (node: ProjectNode): void => {
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => {
        selectedNodeIds.value.add(child.id);
        selectChildNodes(child);
      });
    }
  };

  // 递归取消选中所有子节点
  const unselectChildNodes = (node: ProjectNode): void => {
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => {
        selectedNodeIds.value.delete(child.id);
        unselectChildNodes(child);
      });
    }
  };

  // 获取所有选中的节点
  const getSelectedNodes = (): ProjectNode[] => {
    const selectedNodes: ProjectNode[] = [];

    if (
      !tableInstance ||
      !originalData.value ||
      originalData.value.length === 0
    ) {
      return selectedNodes;
    }

    // 递归遍历所有节点，检查每个节点的复选框状态
    const findSelectedNodes = (
      nodes: ProjectNode[],
      parentPath: string[] = [],
    ) => {
      nodes.forEach((node, nodeIndex) => {
        const currentPath = [...parentPath, nodeIndex.toString()];
        let isChecked = false;
        try {
          let state = null;
          if (props.tableConfig?.mode === "gantt") {
            state = leftTableInstance?.getCellCheckboxState(0, nodeIndex + 1);
          } else {
            state = tableInstance?.getCellCheckboxState(0, nodeIndex + 1);
          }
          isChecked =
            state === true ||
            (typeof state === "object" && (state as any)?.checked);
        } catch (error) {
          console.error("获取复选框状态失败:", error);
        }

        // 如果节点被选中
        if (isChecked) {
          selectedNodes.push(node);
        }

        // 递归检查子节点
        if (node.children && node.children.length > 0) {
          findSelectedNodes(node.children, currentPath);
        }
      });
    };

    // 开始遍历根节点
    findSelectedNodes(originalData.value);

    return selectedNodes;
  };
  const getSelectedNames = (fieldName: string): ProjectNode[] => {
    const selectedAssignees: string[] = [];
    const selectedNodes: ProjectNode[] = [];
    if (!originalData.value || originalData.value.length === 0) {
      return selectedNodes;
    }
    const findSelectedAssignees = (nodes: ProjectNode[]) => {
      nodes.forEach((node, nodeIndex) => {
        let isChecked = false;
        let state = null;
        state = tableInstance?.getCellCheckboxState(0, nodeIndex + 1);
        isChecked =
          state === true ||
          (typeof state === "object" && (state as any)?.checked);
        if (isChecked && node[fieldName]) {
          const value = node[fieldName];
          if (Array.isArray(value)) {
            value.forEach((v) => {
              if (!selectedAssignees.includes(v)) {
                selectedAssignees.push(v);
                selectedNodes.push(node);
              }
            });
          } else {
            if (!selectedAssignees.includes(value)) {
              selectedAssignees.push(value);
              selectedNodes.push(node);
            }
          }
        }
      });
    };
    findSelectedAssignees(originalData.value);
    return selectedNodes;
  };
  const statusVisible = ref(false);
  const position = ref({ left: 0, top: 0 });
  const actions = ref([]);
  // 初始化表格
  const initTable = (isUpdate: boolean) => {
    if (!tableContainer.value) return;

    // 销毁已存在的表格实例
    if (tableInstance && !isUpdate) {
      tableInstance.release();
      tableInstance = null;
    }

    // 根据表格模式注册对应的编辑器
    const mode = props.tableConfig?.mode === "gantt" ? "gantt" : "normal";
    registerCustomEditors(mode, props.fields);

    if (props.tableConfig?.mode === "gantt") {
      // 创建gantt实例
      tableInstance = new VTableGantt.Gantt(
        tableContainer.value,
        tableOption.value,
      );
      leftTableInstance = tableInstance.taskListTableInstance;
      const data = (leftTableInstance as any).internalProps.dataSource;
      data.canChangeOrder = canChangeOrder;
      data.changeOrder = changeOrder;
      if (!leftTableInstance) {
        // console.warn(
        //   "[debug] leftTableInstance not available on gantt instance.",
        // );
        return;
      }
      // 添加单元格点击事件处理操作功能
      leftTableInstance.on("click_cell", (args: any) => {
        const { targetIcon, col, row, field } = args;
        // console.log("click_cell", args);

        // 如果点击的不是moreIcon，则关闭悬浮窗
        if (targetIcon && targetIcon.name !== "moreIcon") {
          closeMoreActionsPopup();
        }
        const cellInfo = leftTableInstance.getCellInfo(col, row);
        if (targetIcon) {
          if (targetIcon.name === "addIcon") {
            const record = cellInfo.originData;
            if (record) {
              addChildNode(leftTableInstance, record as ProjectNode);
              const status = leftTableInstance.getHierarchyState(col, row);
              if (status === "collapse") {
                leftTableInstance.toggleHierarchyState(col, row);
              }
            }
          } else if (targetIcon.name === "ViewIcon") {
            // tableInstance.startEditCell(col, row);
            const record = cellInfo?.originData;
            if (record) {
              emit("on-more-action", "view", cellInfo.originData);
            }
          } else if (targetIcon.name === "deleteIcon") {
            // 删除操作
          } else if (targetIcon.name === "settingIcon") {
            const tableRect = tableContainer.value?.getBoundingClientRect();
            const iconPosition = {
              left: (tableRect?.right || 0) - 50,
              top: (tableRect?.top || 0) - 40,
            };

            const popupPosition = {
              left: iconPosition.left - 230,
              top: iconPosition.top,
            };

            if (showFieldConfigPopup) {
              showFieldConfigPopup(popupPosition);
            }
          }
        } else if (args.field === "_vtable_rowSeries_number") {
          if (!cellInfo) return;
          // 获取所有选中的节点并触发事件
          const selectedNodes = getSelectedNodes();
          if (cellInfo.originData) {
            emit("show:parentRecord", cellInfo.originData);
          }
          emit("show:records", selectedNodes);
        } else if (row > 0) {
          // 点击了操作列
          if (props.routerFields) {
            const hasKey = props.routerFields.includes(field);
            if (hasKey) {
              emit("on-more-action", field, cellInfo.originData);
            }
          }
        } else {
          // 点击了其他区域，关闭悬浮窗
          closeMoreActionsPopup();
          if (col === 1) {
            return;
          }
        }
      });

      leftTableInstance.on("dropdown_menu_click", (args: any) => {
        const { col, row } = args;
        const cellInfo = leftTableInstance.getCellInfo(col, row);

        if (args.menuKey === "添加子记录") {
          addChildNode(leftTableInstance, cellInfo.originData);
          const status = leftTableInstance.getHierarchyState(col, row);
          if (status === "collapse") {
            leftTableInstance.toggleHierarchyState(col, row);
          }
        } else if (args.menuKey === "删除") {
          //获取当前行数据
          const record = leftTableInstance.getCellInfo(args.col, args.row);
          const node = record.originData;

          const tmpFlag = false;
          // 如果父组件提供了删除节点的钩子函数，调用它
          if (props.onDeleteNode && tmpFlag) {
            props.onDeleteNode(node);
          } else {
            // 否则使用默认的删除逻辑
            const no = node.no;
            const rs = removeChildNode(tableOption.value.records, no);
            if (rs) {
              leftTableInstance.setRecords(tableOption.value.records);
            }
          }

          // 触发update事件，让父组件可以同步更新数据
          emit("update:initialData", originalData.value);
        }
      });
      leftTableInstance.on("change_cell_value", (args: any) => {
        // 编辑单元格数据
        // console.log("change_cell_value", args);
        emit("on-more-action", "change_cell_value", args);
      });
      tableInstance.on("change_date_range", (args: any) => {
        // 编辑单元格数据
        // console.log("change_date_range", args);
        emit("on-more-action", "change_date_range", args);
      });
      tableInstance.on("create_dependency_link", (args: any) => {
        console.log("create_dependency_link", args);
        const { link } = args;
        emit("on-more-action", "linkAdd", link);
      });
      tableInstance.on("contextmenu_dependency_link", (args: any) => {
        // console.log("contextmenu_dependency_link", args);
        handleLinkContextMenu(args);
      });
    } else {
      // 创建树表实例
      tableInstance = new VTable.ListTable(
        tableContainer.value,
        tableOption.value,
      );
      // 添加单元格点击事件处理操作功能
      tableInstance.on("click_cell", (args: any) => {
        const { targetIcon, col, row, field } = args;
        // 存储当前行的数据
        const cellInfo = tableInstance.getCellInfo(col, row);
        tempCurrentRowData.value = cellInfo?.originData as ProjectNode | null;
        // console.log("click_cell", args);

        // 如果点击的不是moreIcon，则关闭悬浮窗
        if (targetIcon && targetIcon.name !== "moreIcon") {
          closeMoreActionsPopup();
        }
        if (targetIcon) {
          if (targetIcon.name === "addIcon") {
            console.log("addIcon");
            const record = cellInfo.originData;
            if (record) {
              addChildNode(tableInstance, record as ProjectNode);
              const status = tableInstance.getHierarchyState(col, row);
              if (status === "collapse") {
                tableInstance.toggleHierarchyState(col, row);
              }
            }
          } else if (targetIcon.name === "ViewIcon") {
            // tableInstance.startEditCell(col, row);
            const record = cellInfo?.originData;
            if (record) {
              emit("on-more-action", "view", cellInfo.originData);
            }
          } else if (targetIcon.name === "deleteIcon") {
            // 删除操作
          } else if (targetIcon.name === "settingIcon") {
            const tableRect = tableContainer.value?.getBoundingClientRect();
            const iconPosition = {
              left: (tableRect?.right || 0) - 50,
              top: (tableRect?.top || 0) - 40,
            };

            const popupPosition = {
              left: iconPosition.left - 230,
              top: iconPosition.top,
            };

            if (showFieldConfigPopup) {
              showFieldConfigPopup(popupPosition);
            }
          }
        } else if (args.field === "_vtable_rowSeries_number") {
          if (!cellInfo) return;
          // 获取所有选中的节点并触发事件
          const selectedNodes = getSelectedNodes();
          if (cellInfo.originData) {
            emit("show:parentRecord", cellInfo.originData);
          }
          emit("show:records", selectedNodes);
        } else if (row > 0) {
          // 点击了操作列
          if (props.routerFields) {
            const hasKey = props.routerFields.includes(field);
            if (hasKey && args.cellType !== "switch") {
              // emit("view-node-detail", cellInfo.originData);
              emit("on-more-action", field, cellInfo.originData, args);
            }
          }
        } else {
          // 点击了其他区域，关闭悬浮窗
          closeMoreActionsPopup();
          if (col === 1) {
            return;
          }
        }
      });

      tableInstance.on("dropdown_menu_click", (args: any) => {
        const { col, row } = args;
        const cellInfo = tableInstance.getCellInfo(col, row);

        if (args.menuKey === "添加子记录") {
          addChildNode(tableInstance, cellInfo.originData);
          const status = tableInstance.getHierarchyState(col, row);
          if (status === "collapse") {
            tableInstance.toggleHierarchyState(col, row, true); // 添加第二个参数以满足方法签名要求
          }
        } else if (args.menuKey === "删除") {
          //获取当前行数据
          const record = tableInstance.getCellInfo(args.col, args.row);
          const node = record.originData;

          const tmpFlag = false;
          // 如果父组件提供了删除节点的钩子函数，调用它
          if (props.onDeleteNode && tmpFlag) {
            props.onDeleteNode(node);
          } else {
            // 否则使用默认的删除逻辑
            const no = node.no;
            const rs = removeChildNode(tableOption.value.records, no);
            if (rs) {
              tableInstance.setRecords(tableOption.value.records);
            }
          }

          // 触发update事件，让父组件可以同步更新数据
          emit("update:initialData", originalData.value);
        }
      });
      tableInstance.on(
        VTable.ListTable.EVENT_TYPE.SWITCH_STATE_CHANGE,
        (e: any) => {
          const { col, row } = e;
          // console.log("SWITCH_STATE_CHANGE", e);
          const cellInfo = tableInstance.getCellInfo(col, row);
          emit("on-more-action", e.field, cellInfo.originData, {
            field: e?.cellHeaderPaths?.colHeaderPaths[0]?.field,
            checked: e.checked,
          });
        },
      );
      // tableInstance.on("change_header_position_start", (args: any) => {
      //   console.log("change_header_position_start", args);
      // });
      // tableInstance.on("change_header_position", (args: any) => {
      //   console.log("change_header_position", args);
      // });
      // tableInstance.on("changing_header_position", (args: any) => {
      //   console.log("changing_header_position", args);
      // });
      tableInstance.on(VTable.ListTable.EVENT_TYPE.MOUSEENTER_CELL, (args) => {
        tableInstance.stateManager.showHorizontalScrollBar(true);
      });
      tableInstance.on(VTable.ListTable.EVENT_TYPE.MOUSELEAVE_CELL, (args) => {
        tableInstance.stateManager.showHorizontalScrollBar(false);
      });
    }

    tableInstance.on("change_cell_value", (args: any) => {
      // 编辑单元格数据
      emit("update:saveField", originalData.value);
      const record = tableInstance.getCellInfo(args.col, args.row);
      console.log("change_cell_value", args, record);
      // emit("on-more-action", "change_cell_value", record.originData);
      emit("on-more-action", "change_cell_value_origin", record);
    });
    tableInstance.on("dblclick_cell", (args: any) => {
      // 双击单元格数据
      // console.log("dblclick_cell", args);
      // emit("update:saveField", originalData.value);
    });

    tableInstance.on(
      VTable.ListTable.EVENT_TYPE.CHANGE_HEADER_POSITION_START,
      (args: any) => {
        dragSourceRow = args.row ?? null;
        if (dragSourceRow !== null) createHighlight(dragSourceRow);
      },
    );
    tableInstance.on(
      VTable.ListTable.EVENT_TYPE.CHANGING_HEADER_POSITION,
      (args: any) => {
        if (dragSourceRow === null) return;
        // 使用绝对 Y（考虑表格偏移）
        const absoluteY = args.y;
        const targetRow = args.row;
        currentHoverRow = targetRow ?? null;

        if (currentHoverRow !== null) {
          // 计算目标行信息
          const bounds = getRowBounds(tableInstance, args.row);
          if (!bounds) return;

          // 统一坐标系：rowTop/bottom 与 relativeY 都在内容区坐标系
          const rowTop = bounds.top;
          const rowBottom = bounds.bottom;
          const rowHeight = rowBottom - rowTop;
          const rowCenter = rowTop + rowHeight / 2;
          const relativeY = absoluteY;
          // 中段判断带
          const centerBand = rowHeight * 0.3;
          const middleTop = rowCenter - centerBand;
          const middleBottom = rowCenter + centerBand;

          // 创建并显示蓝线
          createBlueLine(tableInstance.container);
          createPreviewBox(tableInstance.container, args.row);

          // 区域判断
          if (relativeY >= middleTop && relativeY <= middleBottom) {
            // 中间（子节点提示）
            currentY = relativeY;
            targetY = relativeY;
            blueLineDiv!.style.opacity = "1";
            blueLineDiv!.dataset.type = "child";
            blueLineDiv!.style.backgroundColor = "#4caf50";
            blueLineDiv!.style.left = "24px";
            blueLineDiv!.style.width = "calc(100% - 24px)";
            previewBoxDiv!.style.opacity = "0";
          } else {
            currentY = relativeY - 18;
            blueLineDiv!.style.opacity = "0";
            blueLineDiv!.dataset.type = "";
            // 显示透明占位方框
            targetY = relativeY - 18;
            previewBoxDiv!.style.opacity = "1";
          }
          // 启动动画帧（如果尚未启动）
          if (!animationFrame) rafLoop();
        } else {
          hideBlueLine();
        }
      },
    );
    tableInstance.on(
      VTable.ListTable.EVENT_TYPE.CHANGE_HEADER_POSITION,
      (args: any) => {
        clearHighlight();
        clearPreviewBox();
        // console.log(
        //   "CHANGE_HEADER_POSITION",
        //   dragSourceRow,
        //   currentHoverRow,
        //   tableInstance.records,
        // );
        // 发射拖拽完成事件，传递拖拽信息
        if (dragSourceRow !== null && currentHoverRow !== null) {
          // console.log(dragSourceRow, currentHoverRow, "2121212121");
          const sourceRecord = tableInstance.getRecordByCell(0, dragSourceRow);
          const targetRecord = tableInstance.getRecordByCell(
            0,
            currentHoverRow,
          );
          // if (sourceRecord && targetRecord) {
          //   const dragData = {
          //     draggedId:
          //       sourceRecord.originData?.idChain || sourceRecord.idChain,
          //     targetId:
          //       targetRecord.originData?.idChain || targetRecord.idChain,
          //     position: blueLineDiv?.dataset.type || "after",
          //   };
          //   emit("drag-completed", dragData);
          // }
        }

        dragSourceRow = null;
        currentHoverRow = null;
      },
    );
    tableInstance.on(
      VTable.ListTable.EVENT_TYPE.CHANGE_HEADER_POSITION_FAIL,
      (args: any) => {
        clearHighlight();
        clearPreviewBox();
        dragSourceRow = null;
        currentHoverRow = null;
      },
    );
    applyLineHeight();
  };
  let highlightDiv: HTMLDivElement | null = null;
  let blueLineDiv: HTMLDivElement | null = null;
  let dragSourceRow: number | null = null;
  let currentHoverRow: number | null = null;
  let animationFrame: number | null = null;
  let previewBoxDiv: HTMLDivElement | null = null;
  let currentY = 0;
  let targetY = 0;
  // 创建蓝线（若已存在则复用）
  function createBlueLine(container: HTMLElement) {
    if (!blueLineDiv) {
      blueLineDiv = document.createElement("div");
      blueLineDiv.style.position = "absolute";
      blueLineDiv.style.top = "0px"; // 用 transform 来移动
      blueLineDiv.style.height = "2px";
      blueLineDiv.style.left = "0px";
      blueLineDiv.style.width = "100%";
      blueLineDiv.style.backgroundColor = "#2196f3";
      blueLineDiv.style.pointerEvents = "none";
      blueLineDiv.style.opacity = "0";
      blueLineDiv.style.transition = "opacity 0.12s linear";
      blueLineDiv.style.transform = "translateY(0px)";
      container.appendChild(blueLineDiv);
      currentY = targetY = 0;
    }
  }
  // 初始化拖拽占位方框
  const createPreviewBox = (container: HTMLElement, row: number) => {
    if (!previewBoxDiv) {
      const rect = tableInstance.getCellRect(0, row);
      if (!rect) return;
      previewBoxDiv = document.createElement("div");
      previewBoxDiv.style.position = "absolute";
      previewBoxDiv.style.top = "0px";
      previewBoxDiv.style.left = "0px";
      previewBoxDiv.style.width = "100%";
      previewBoxDiv.style.backgroundColor = "rgba(33, 150, 243, 0.1)"; // 半透明
      previewBoxDiv.style.height = rect.height + "px";
      previewBoxDiv.style.borderRadius = "4px";
      previewBoxDiv.style.pointerEvents = "none";
      previewBoxDiv.style.transition = "opacity 0.2s";
      previewBoxDiv.style.opacity = "0";
      previewBoxDiv.style.zIndex = "9999";
      container.appendChild(previewBoxDiv);
    }
  };

  // 隐藏并重置蓝线
  const hideBlueLine = () => {
    if (!blueLineDiv) return;
    blueLineDiv.style.opacity = "0";
    blueLineDiv.style.left = "0px";
    blueLineDiv.style.width = "100%";
    blueLineDiv.style.backgroundColor = "#2196f3";
    if (animationFrame) {
      cancelAnimationFrame(animationFrame);
      animationFrame = null;
    }
  };

  const updateNodeIds = (node: ProjectNode, newPrefix: string): void => {
    node.id = newPrefix;
    node.no = newPrefix;
    if (node.children && node.children.length > 0) {
      node.children.forEach((child, index) => {
        const childPrefix = `${newPrefix}-${index + 1}`;
        updateNodeIds(child, childPrefix);
      });
    }
  };
  // 平滑更新位置（线性插值）
  const rafLoop = () => {
    if (!blueLineDiv && !previewBoxDiv) {
      animationFrame = null;
      return;
    }
    // 平滑动画
    currentY += (targetY - currentY) * 0.25;
    if (blueLineDiv && blueLineDiv.style.opacity === "1") {
      blueLineDiv.style.transform = `translateY(${currentY}px)`;
    }
    if (previewBoxDiv && previewBoxDiv.style.opacity === "1") {
      previewBoxDiv.style.transform = `translateY(${currentY}px)`;
    }
    if (Math.abs(currentY - targetY) > 0.5) {
      animationFrame = requestAnimationFrame(rafLoop);
    } else {
      animationFrame = null;
      currentY = targetY;
    }
  };

  // 计算整行 top/bottom（遍历列寻找边界；有回退）
  const getRowBounds = (tableInstance: any, row: number) => {
    const r = tableInstance.getCellRect
      ? tableInstance.getCellRect(0, row)
      : null;
    if (!r) return null;
    return { top: r.top, bottom: r.bottom };
  };

  const createHighlight = (row: number) => {
    const rect = tableInstance.getCellRect(0, row);
    if (!rect) return;
    if (!highlightDiv) {
      highlightDiv = document.createElement("div");
      highlightDiv.style.position = "absolute";
      highlightDiv.style.background = "rgba(0, 0, 0, 0.2)";
      highlightDiv.style.pointerEvents = "none";
      tableInstance.container.appendChild(highlightDiv);
    }
    highlightDiv.style.top = rect.top + "px";
    highlightDiv.style.left = rect.left + "px";
    highlightDiv.style.width = 100 + "%";
    highlightDiv.style.height = rect.height + "px";
  };
  const clearHighlight = () => {
    highlightDiv?.remove();
    highlightDiv = null;
    blueLineDiv?.remove();
    blueLineDiv = null;
  };
  const clearPreviewBox = () => {
    previewBoxDiv?.remove();
    previewBoxDiv = null;
  };

  function handleMakeChild(sourceNode, targetNode) {
    // 1. 拷贝原始数据
    const newRecords = JSON.parse(
      JSON.stringify(tableInstance.dataSource.records),
    );
    // 2. 删除原节点（递归删除）
    removeNode(newRecords, sourceNode.id);
    // 3. 插入为子节点
    const target = findNode(newRecords, targetNode.id);
    target.children = target.children || [];
    target.children.push(sourceNode);
    // 4. 更新数据源
    tableInstance.updateDataSource({ records: newRecords });
    tableInstance.scenegraph.updateNextFrame();
    console.log(`✅ 已将 ${sourceNode.name} 变为 ${targetNode.name} 的子节点`);
  }
  function removeNode(nodes, id) {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children && removeNode(nodes[i].children, id)) return true;
    }
    return false;
  }
  function findNode(nodes, id) {
    for (const node of nodes) {
      if (node.id === id) return node;
      if (node.children) {
        const found = findNode(node.children, id);
        if (found) return found;
      }
    }
    return null;
  }

  const removeChildNode = (list: ProjectNode[], no: string): boolean => {
    if (!list || !Array.isArray(list) || !no) return false;

    for (let i = 0; i < list.length; i++) {
      const node = list[i];

      if (node.no === no) {
        list.splice(i, 1);

        const parentNoParts = no.split("-");
        // 如果不是顶级节点
        if (parentNoParts.length > 1) {
          const parentNo = parentNoParts.slice(0, -1).join("-");
          // 遍历剩余的同级节点，重新编号
          for (let j = i; j < list.length; j++) {
            const newNo = `${parentNo}-${j + 1}`; // j 是删除后数组的索引（从0开始），但节点编号从1开始
            updateNodeIds(list[j], newNo);
          }
        } else {
          // 顶级节点的情况
          for (let j = i; j < list.length; j++) {
            const oldNodeNo = list[j].no;
            const oldNodeNoParts = oldNodeNo.split("-");
            if (oldNodeNoParts.length === 1) {
              // 直接更新顶级节点
              const newNo = `${j + 1}`;
              updateNodeIds(list[j], newNo);
            }
          }
        }

        return true;
      }

      if (node.children && node.children.length > 0) {
        const found = removeChildNode(node.children, no);

        if (found) {
          // 当子节点列表为空时，删除children属性
          if (node.children.length === 0) {
            delete node.children;
          }
          return true;
        }
      }
    }

    return false;
  };
  // 更新甘特图连线的方法
  const updateLinks = (links: any[]) => {
    // console.log("updateLinks", links);
    if (props.tableConfig?.mode === "gantt" && tableInstance) {
      try {
        links.forEach((link) => {
          const { linkedFromTaskKey, linkedToTaskKey, direction, id } = link;
          // console.log("linkedFromTaskKey", linkedFromTaskKey);
          // console.log("linkedToTaskKey", linkedToTaskKey);
          // console.log("direction", direction);
          tableInstance.addLink({
            id: id,
            type: direction,
            linkedFromTaskKey: linkedFromTaskKey,
            linkedToTaskKey: linkedToTaskKey,
          });
        });
        // console.log("连线已更新");
      } catch (error) {
        console.error("更新甘特图连线失败:", error);
      }
    }
  };
  const deleteLink = (link: any) => {
    // console.log("deleteLink", link);
    if (props.tableConfig?.mode === "gantt" && tableInstance) {
      tableInstance.deleteLink(link);
      // console.log("连线已删除");
      setTimeout(() => {
        tableInstance.scenegraph.refreshAll();
      }, 100);
    }
  };

  // 获取表格实例
  const getTableInstance = () => {
    return new Promise((resolve, reject) => {
      // 如果实例已经存在，直接返回
      if (tableInstance) {
        console.log("CLTable: 直接返回已存在的tableInstance");
        return resolve(tableInstance);
      }

      // 设置最大尝试次数和间隔
      const maxAttempts = 10;
      const interval = 100;
      let attempts = 0;

      const checkInstance = () => {
        attempts++;

        if (tableInstance) {
          console.log("CLTable: 成功获取tableInstance");
          resolve(tableInstance);
        } else if (attempts >= maxAttempts) {
          console.error("CLTable: 超过最大尝试次数，无法获取tableInstance");
          reject(new Error("表格实例初始化超时"));
        } else {
          console.log(
            `CLTable: 尝试获取tableInstance (${attempts}/${maxAttempts})`,
          );
          setTimeout(checkInstance, interval);
        }
      };

      checkInstance();
    });
  };

  // 获取甘特表格实例
  const getLeftTableInstance = () => {
    return new Promise((resolve, reject) => {
      const maxAttempts = 10;
      const interval = 100;
      let attempts = 0;

      const checkInstance = () => {
        attempts++;

        if (leftTableInstance) {
          console.log("CLTable: 成功获取leftTableInstance");
          resolve(leftTableInstance);
        } else if (attempts >= maxAttempts) {
          console.error("CLTable: 超过最大尝试次数，无法获取leftTableInstance");
          reject(new Error("左侧表格实例初始化超时"));
        } else {
          console.log(
            `CLTable: 尝试获取leftTableInstance (${attempts}/${maxAttempts})`,
          );
          setTimeout(checkInstance, interval);
        }
      };

      checkInstance();
    });
  };

  defineExpose({
    addChildNode,
    updateLinks,
    deleteLink,
    getSelectedNames,
    // 提供方法而不是直接暴露实例
    getTableInstance,
    getLeftTableInstance,
  });

  // 处理搜索
  const handleSearch = () => {
    if (!tableInstance) return;

    const keyword = searchKeyword.value.toLowerCase().trim();
    if (!keyword) {
      tableInstance.setRecords(originalData.value);
      return;
    }

    // 递归搜索函数
    const searchInTree = (
      records: ProjectNode[],
      keyword: string,
    ): ProjectNode[] => {
      return records.reduce((acc: ProjectNode[], record) => {
        const match =
          record.name.toLowerCase().includes(keyword) ||
          record.assignee.toLowerCase().includes(keyword) ||
          // record.priority.toLowerCase().includes(keyword) ||
          record.status.toLowerCase().includes(keyword);

        if (record.children && record.children.length > 0) {
          const filteredChildren = searchInTree(record.children, keyword);
          if (match || filteredChildren.length > 0) {
            const newRecord = { ...record };
            if (filteredChildren.length > 0) {
              newRecord.children = filteredChildren;
            }
            acc.push(newRecord);
          }
        } else if (match) {
          acc.push({ ...record });
        }

        return acc;
      }, []);
    };

    const filteredData = searchInTree(originalData.value, keyword);
    tableInstance.setRecords(filteredData);
  };

  // 监听搜索关键词变化
  watch(searchKeyword, handleSearch);

  const handleClickOutsideLinkPopup = (event: MouseEvent) => {
    if (showLinkDeletePopup.value) {
      const popup = document.querySelector(".link-delete-popup");
      if (popup && !popup.contains(event.target as Node)) {
        closeLinkDeletePopup();
      }
    }
  };
  const isFieldDisabled = (field: DynamicField, args: any): boolean => {
    if (!field.disable) return false;
    if (typeof field.disable === "boolean") {
      return field.disable;
    }
    if (typeof field.disable === "string") {
      const record = originalData.value?.[args.row - 1];
      return Boolean(record?.[field.disable]);
    }
    return false;
  };
  // 组件挂载时初始化表格
  onMounted(() => {
    // 立即初始化表格（因为默认显示需求列表选项卡）
    initTable(true);
    applyLineHeight();

    // 添加窗口滚动和调整大小事件监听器
    window.addEventListener("scroll", updatePopupPositionOnScrollOrResize);
    window.addEventListener("resize", updatePopupPositionOnScrollOrResize);

    // 添加点击外部区域关闭连线删除悬浮窗的事件监听器
    document.addEventListener("click", handleClickOutsideLinkPopup);

    // 监听Tab切换，确保在切换回需求列表时表格仍能正确显示
    if (props.activeTab !== undefined) {
      watch(
        () => props.activeTab,
        (newTab) => {
          if (newTab === 2 && tableContainer.value) {
            initTable(false);
            // 切换Tab后重新应用行高设置
            applyLineHeight();
          }
        },
      );
    }
    // 监听fields变化，动态更新表格列
    watch(
      () => props.fields,
      () => {
        if (tableContainer.value) {
          initTable(true);
          // 列更新后重新应用行高设置
          applyLineHeight();
        }
      },
      { deep: true },
    );
    nextTick(() => {
      setTimeout(() => {
        if (props.tableConfig?.mode === "gantt") {
          if (!tableInstance) return;
          props.initialLinks?.map((link) => {
            tableInstance.addLink(link);
          });
        }
      }, 1000);
    });
  });
  const handleStatusAction = (action: string) => {
    emit("on-more-action", "taskStatusChange", action);
  };
  const updateNode = (node: ProjectNode | null) => {
    if (!node) return;
    // 查找并更新原始数据中的节点
    const updateNodeInTree = (nodes: ProjectNode[]): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === node.id) {
          // 找到对应节点，更新它
          nodes[i] = { ...nodes[i], ...node };
          return true;
        }

        // 递归查找子节点
        if (nodes[i].children && nodes[i].children!.length > 0) {
          if (updateNodeInTree(nodes[i].children!)) {
            return true;
          }
        }
      }
      return false;
    };
    // 更新数据源
    updateNodeInTree(originalData.value);
    // 如果表格实例存在，更新表格显示
    if (tableInstance) {
      tableInstance.setRecords(originalData.value);
    }
    // 触发更新事件通知父组件
    emit("update:initialData", originalData.value);
  };
  // 组件卸载时销毁表格
  onUnmounted(() => {
    if (tableInstance) {
      tableInstance.release();
      tableInstance = null;
    }

    // 移除窗口滚动和调整大小事件监听器
    window.removeEventListener("scroll", updatePopupPositionOnScrollOrResize);
    window.removeEventListener("resize", updatePopupPositionOnScrollOrResize);

    // 移除点击外部区域关闭连线删除悬浮窗的事件监听器
    document.removeEventListener("click", handleClickOutsideLinkPopup);
  });
</script>

<style lang="scss" scoped>
  $primary-color: #1aa1fb;
  $success-color: #52c41a;
  $warning-color: #fa8c16;
  $danger-color: #ff4d4f;
  $text-color: #666666;
  $light-text: rgba(0, 0, 0, 0.5);
  $border-color: #e0e0e0;
  $background-color: #f8f9fa;
  $hover-bg: #e6f7ff;

  .tree-table-container {
    .table-container {
      width: 100%;
      overflow: hidden;
      background-color: #ffffff;
      position: relative;
      height: calc(100vh - 90px);
    }
  }

  // 自定义VTable样式
  :deep(.v-table-header) {
    background-color: $background-color !important;
    border-bottom: 2px solid $primary-color !important;
  }

  :deep(.v-table-cell) {
    border-color: $border-color !important;
    transition: background-color 0.2s;
    position: relative !important;

    &:hover {
      background-color: #f6f7fa !important;
    }
  }

  :deep(.v-table-row) {
    &:hover {
      background-color: #f6f7fa !important;
    }
  }

  :deep(.v-table-row-selected) {
    background-color: $hover-bg !important;
  }

  :deep(.v-table-checkbox) {
    cursor: pointer;
  }

  .other-content {
    padding: 20px;
    text-align: center;
    color: $light-text;
  }

  // 操作按钮悬停显示效果
  :deep(.cell-hover-effect) {
    position: relative !important;
    z-index: 10;
  }

  // 添加渐入和缩放动画效果
  @keyframes fadeInScale {
    from {
      opacity: 0;
      transform: scale(0.9);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }

  // 添加子节点图标的样式
  .add-child-icon {
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    background-color: white !important;
    border-radius: 50% !important;
    border: 1px solid #ff4d4f !important;
    color: #ff4d4f !important;
    font-size: 14px !important;
    width: 24px !important;
    height: 24px !important;
    cursor: pointer !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
    z-index: 1000 !important;
    padding: 0 !important;
    margin: 0 !important;
    transition: all 0.3s ease !important;
    animation: fadeInScale 0.3s ease forwards !important;

    &:hover {
      transform: scale(1.1) !important;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
    }
  }

  // 连线删除悬浮窗样式
  .link-delete-popup {
    position: absolute;
    z-index: 2000;
    pointer-events: auto;
    animation: fadeInScale 0.2s ease-out;
  }

  .popup-content {
    background: white;
    border-radius: 6px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    border: 1px solid $border-color;
    overflow: hidden;
    min-width: 100px;
  }

  .delete-action {
    padding: 8px 16px;
    color: $danger-color;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 12px;
    text-align: center;

    &:hover {
      background-color: $hover-bg;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 5px;
    border-top: 1px solid #f2f3f5;
    .el-pagination {
      gap: 10px;
    }
  }
</style>
